/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import ControllerInterface.IControllerStatsMap;
import ViewInterface.IViewStats;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;

/**
 *
 * @author Fabian
 */
public class ViewStats extends JPanel implements IViewStats, ActionListener {

    /**
     * Time series for total memory used.
     */
    private TimeSeries total;
    private IControllerStatsMap myController;
    JButton botonStop;
    JButton botonResume;
    JFrame frame;
    ViewStats panel;
    DataGenerator dg;
    JLabel speed;
    /**
     * Time series for current memory.
     */
    private TimeSeries current;

    /**
     * Creates a new application.
     *     
* @param maxAge the maximum age (in milliseconds).
     */
    public ViewStats(int maxAge) {
        super(new BorderLayout());
        
        this.total = new TimeSeries("Total datos almacenados", Millisecond.class);
        this.total.setMaximumItemAge(maxAge);
        this.current = new TimeSeries("Datos escritos", Millisecond.class);
        this.current.setMaximumItemAge(maxAge);
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(this.total);
        dataset.addSeries(this.current);

        DateAxis domain = new DateAxis("Tiempo");
        NumberAxis range = new NumberAxis("Datos (KBytes)");

        domain.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        range.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        domain.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));
        range.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));

        XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false);
        renderer.setSeriesPaint(0, Color.red);
        renderer.setSeriesPaint(1, Color.green);
        renderer.setStroke(new BasicStroke(3f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL));
        XYPlot plot = new XYPlot(dataset, domain, range, renderer);
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        domain.setAutoRange(true);
        domain.setLowerMargin(0.0);
        domain.setUpperMargin(0.0);
        domain.setTickLabelsVisible(true);
        range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        JFreeChart chart = new JFreeChart("Gráfico de extracción",
                new Font("SansSerif", Font.BOLD, 24), plot, true);
        chart.setBackgroundPaint(Color.white);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(4, 4, 4, 4),
                BorderFactory.createLineBorder(Color.black)));
        ChartPanel chartPanel2 = new ChartPanel(chart);
        chartPanel2.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(4, 4, 4, 4),
                BorderFactory.createLineBorder(Color.YELLOW)));
        chartPanel.setBounds(5, 5, 300, 140);
        chartPanel2.setBounds(305, 5, 300, 140);
        add(chartPanel, BorderLayout.CENTER );
//        add(chartPanel2, BorderLayout.AFTER_LINE_ENDS);
    }

    /**
     * 
     */
    public ViewStats() {
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == botonStop) {
            this.myController.stopExtraction();
            dg.stop();
        }
        if (e.getSource() == botonResume) {
            this.myController.resumeExtraction();
        }
    }

   
    private void addTotalObservation(double y) {
        this.total.add(new Millisecond(), y);
    }

    private void addFreeObservation(double y) {
        this.current.add(new Millisecond(), y);
    }
    
    private void addSpeedObservation(double y) {
        this.speed.setText("Velocidad: "+Math.round(y*Math.pow(10,3))/Math.pow(10,3)+"[KB/s]");
        this.speed.repaint();
        
    }

    /**
     * The data generator.
     */
    class DataGenerator extends Timer implements ActionListener {

        /**
         * Constructor.
         *         
* @param interval the interval (in milliseconds)
         */
        IControllerStatsMap stats;
        int time;

        DataGenerator(int interval, IControllerStatsMap stats) {
            super(interval, null);
            addActionListener(this);
            this.stats = stats;
        }

        /**
         * Adds a new current/total memory reading to the dataset.
         *         
* @param event the action event.
         *
         */
        public void actionPerformed(ActionEvent event) {
            long[] s = stats.getSizeFile();
            addTotalObservation(s[0]/1024.0);
            addFreeObservation(s[1]/1024.0);
            time = time + this.getDelay();
            addSpeedObservation((s[0]/1024.0)*1000/time);
        }
    }

    /**
     * 
     */
    @Override
    public void initStats() {
        frame = new JFrame("Estadísticas");
        JPanel panelBotones = new JPanel();
        JPanel panelSpeed = new JPanel();
        panel = new ViewStats(300000);
        panel.speed = new JLabel();
        panelSpeed.add(panel.speed);
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        botonStop = new JButton("Detener extracción");
        botonStop.setBounds(10, 90, 90, 30);
        botonStop.addActionListener(this);
        botonResume = new JButton("Play/Pausa");
        botonResume.setBounds(10, 90, 90, 30);
        botonResume.addActionListener(this);
        panelBotones.add(botonStop);
        panelBotones.add(botonResume);
        panelBotones.add(panelSpeed);
        frame.getContentPane().add(panelBotones, BorderLayout.AFTER_LAST_LINE);
        frame.setBounds(200, 120, 600, 280);
        frame.setVisible(true);
        dg = panel.new DataGenerator(100, myController);
        dg.start();
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                dg.stop();
                frame.dispose();
            }
        });
    }

    /**
     * 
     * @param controlador
     */
    @Override
    public void setController(IControllerStatsMap controlador) {
        myController = controlador;
    }

    /**
     * 
     */
    @Override
    public void setNewStats() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
